//
//  ZQOAuthViewController.swift
//  Created on 2019/12/12
//  Description <#文件描述#>
//  Copyright © 2019 Huami inc. All rights reserved.
//  @author huangjianwen(huangjianwen@huami.com)    
//

import UIKit
import WebKit
import SVProgressHUD

class ZQOAuthViewController: UIViewController {

    private lazy var webview = WKWebView()
    
    override func loadView() {
        view = webview
        webview.scrollView.isScrollEnabled = false
        title = "登陆新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        ZQNetWorkManager.shared.loadAccessToken(code: "f1d0573de1473a790c609913dc31223c") { (isSuccess) in

            if  isSuccess {
                // 1.跳转界面 通过通知
                NotificationCenter.default.post(
                    name: NSNotification.Name(ZQUserLoginSuccessNotification),
                    object: nil,
                    userInfo: nil
                )

                // 2.关闭窗口
                self.close()
            } else {
                SVProgressHUD.showError(withStatus: "网络请求失败")
            }
        }
//        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
//        guard let url = URL(string: urlString) else {
//                return
//        }
//
//         let request = URLRequest(url: url)
//        webview.uiDelegate = self
//        webview.navigationDelegate = self
//        webview.load(request)
    }
    
    // MARK: - Navigation
   @objc private func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }

    @objc private func autoFill(){
        // 1.准备js ;不能省略代表两个语句
        let js = "document.getElementById('userId').value = '15178607567';" + "document.getElementById('passwd').value = 'h6611469';"
        // 2.让webview执行js
        webview.evaluateJavaScript(js, completionHandler: nil)
    }
}

extension ZQOAuthViewController: WKUIDelegate, WKNavigationDelegate {
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if webView.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return decisionHandler(.allow)
        }

        if webView.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return decisionHandler(.cancel)
        }

        // 3.从query中取出授权码
//'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
        let a = webView.url?.query
        let b = "code=".endIndex
        let code = String(a![b...])
        print("获取授权码 - \(code)")

        ZQNetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in

            if  isSuccess {
                // 1.跳转界面 通过通知
                NotificationCenter.default.post(
                    name: NSNotification.Name(ZQUserLoginSuccessNotification),
                    object: nil,
                    userInfo: nil
                )

                // 2.关闭窗口
                self.close()
            } else {
                SVProgressHUD.showError(withStatus: "网络请求失败")
            }
        }
        return decisionHandler(.allow)
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("开始加载")
        SVProgressHUD.show()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("加载完毕")
        SVProgressHUD.dismiss()
    }
}
